from flask import make_response, request, jsonify
# from models  import Emp,Dept
from flask_restful import marshal, fields

from db import db
from models import Teacher, resoure_fields
from . import user_bp

import jwt


# 定义user下的所有操作
@user_bp.route("/query",methods=['GET','POST'])
def query():
    teacher = Teacher.query.offset(0).limit(2).all()
    data = {}
    data['resultCode'] = 200
    data['info'] = marshal(teacher, resoure_fields)
    resp = make_response(data)
    resp.status = 200
    return resp



@user_bp.route("/add",methods=['GET','POST'])
def add():
    status = 200
    req = request.get_json()['data']
    print(req)
    teacher_id = req['teacher_id']
    teacher_name = req['teacher_name']
    teacher_sex = req['teacher_sex']
    teacher_account = req['teacher_account']
    teacher_password = req['teacher_password']
    teacher_title = req['teacher_title']
    teacher_phone = req['teacher_phone']

    teacher = Teacher(teacher_id=teacher_id,teacher_name=teacher_name,teacher_sex=teacher_sex,teacher_account=teacher_account,
                teacher_password=teacher_password,teacher_title=teacher_title,teacher_phone=teacher_phone,is_admin=1)

    try:
        db.session.add(teacher)
        db.session.commit()
    except Exception as e:
        print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
        print(e)
        status=405



    # 对象被插入数据库后，主键会被自动设置回对象
    print(teacher)
    data = {}
    data['resultCode'] = 200
    resp = make_response(data)
    resp.status=status
    return resp

@user_bp.route("/login",methods=['GET','POST'])
def login():
    data = request.get_json()
    data = {}
    data['userName'] = request.get_json()['userName']
    encoded_jwt = jwt.encode({'userName': data['userName']}, 'secret', algorithm='HS256')
    data['resultCode'] = 200
    data['token'] = encoded_jwt
    resp = make_response(data)
    resp.status=200
    return resp

